package com.frank.libandroid.util;

import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

public class CountDownUtil {
    private static final String TAG = "CountDownUtil";

    public static void startCountDown(TextView textView, int seconds) {
        CharSequence text = textView.getText();
        Object tag = textView.getTag();
        if (tag != null && tag instanceof CountDownTimer) {
            CountDownTimer countDownTimer = (CountDownTimer) tag;
            countDownTimer.cancel();
        }
        CountDownTimer countDownTimer = new CountDownTimer(seconds * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                textView.setText(String.valueOf((millisUntilFinished + 500) / 1000) + "s");
                Log.d(TAG, "onTick() called with: millisUntilFinished = [" + millisUntilFinished + "]");
            }

            @Override
            public void onFinish() {
                textView.setText(text);
                textView.setEnabled(true);

            }
        };
        textView.setEnabled(false);
        countDownTimer.start();
        textView.setTag(countDownTimer);
        textView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(@NonNull View v) {

            }

            @Override
            public void onViewDetachedFromWindow(@NonNull View v) {
                Object tag = textView.getTag();
                if (tag != null && tag instanceof CountDownTimer) {
                    CountDownTimer countDownTimer = (CountDownTimer) tag;
                    countDownTimer.cancel();
                }
            }
        });
    }
}
